package main

import (
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	jaegercfg "github.com/uber/jaeger-client-go/config"
	"go-jaeger/gin-jaeger/otgrpc"
	"go-jaeger/gin-jaeger/proto"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"net/http"
)

func main() {
	r := gin.Default()
	r.Use(tracer())
	r.GET("/ping", ping)
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

func ping(ctx *gin.Context) {
	conn, _ := grpc.Dial("127.0.0.1:8081",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer())))
	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)
	client := proto.NewGreeterClient(conn)
	hello, _ := client.SayHello(context.WithValue(context.Background(), "ginContext", ctx), &proto.HelloRequest{Name: "GRPC"})
	ctx.JSON(http.StatusOK, hello)
}

func tracer() gin.HandlerFunc {
	return func(context *gin.Context) {
		cfg := jaegercfg.Configuration{
			Sampler: &jaegercfg.SamplerConfig{
				Type:  jaeger.SamplerTypeConst,
				Param: 1,
			},
			Reporter: &jaegercfg.ReporterConfig{
				LogSpans:           true,
				LocalAgentHostPort: "192.168.193.128:6831",
			},
			ServiceName: "ServiceName2",
		}
		tracer, closer, err := cfg.NewTracer(jaegercfg.Logger(jaeger.StdLogger))
		if err != nil {
			panic(err)
		}
		defer closer.Close()
		startSpan := tracer.StartSpan(context.Request.URL.Path)
		defer startSpan.Finish()
		context.Set("tracer", tracer)
		context.Set("parentSpan", startSpan)
		context.Next()
	}
}
